<?php


declare(strict_types=1);

namespace app\seller\controller\admin;

use app\seller\model\Category as CategoryModel;
use app\shop\model\Category as shopCategoryModel;
use sheep\controller\Backend;
use think\facade\Db;
use think\Request;
use think\Response;
use sheep\library\Tree;
//类目表
class Category extends Backend
{

    protected $model = null;
    protected $shopCategorymodel = null;

    protected function initialize()
    {
        $this->model = new CategoryModel;
        $this->shopCategorymodel = new shopCategorymodel;
    }


    /**
     * 查看
     *
     * @return Response
     */
    public function list(Request $request): Response
    {
        $admin = $this->auth()->user();

        $params = $this->request->only([
            'type'
        ]);

        // 自定义排序规则
        $order = "CASE 
                    WHEN ca.audit_status = 'normal' THEN 1 
                    WHEN ca.audit_status = 'apply' THEN 2 
                    WHEN ca.audit_status = 'disabled' THEN 3 
                    WHEN ca.audit_status = 'reject' THEN 4 
                    ELSE 5 
                  END";

        // 查询所有最底级的分类，并关联审核表
        $list = $this->shopCategorymodel->with(['parent', 'audit' => function($query) {
            $query->field('category_id, audit_status');
        }])
            ->alias('c')
            ->leftJoin('(SELECT * FROM saas_organ_category WHERE organ_id = ' . $admin->organ_id . ') ca', 'ca.category_id = c.id')
            ->where('c.type',$params['type'])
            ->whereNotIn('c.id', function ($query) {
                $query->name('shop_category')
                    ->distinct(true)
                    ->whereNotNull('parent_id')
                    ->field('parent_id');
            })
            ->field('c.*,ca.audit_status,ca.id as c_id,ca.industry_qualification,ca.audit_status,ca.remarks')
            ->orderRaw($order)
            ->select();

        // 分组到两个数组,区分审核需要上传文件的和不需要文件的
        $proofRequired0 = [];
        $proofRequired1 = [];

        foreach ($list as $category) {
            if ($category['proof_required'] == 0) {
                $proofRequired0[] = $category;
            } else {
                $proofRequired1[] = $category;
            }
        }

        // 返回结果
        return success('获取成功', [
            'proof_required_0' => $proofRequired0,
            'proof_required_1' => $proofRequired1
        ]);
    }





    /**
     * 申请添加
     *
     * @return \think\Response
     */
    public function add(Request $request)
    {
        $admin = $this->auth()->user();

        $params = $this->request->only(['type','category_id', 'industry_qualification']);

        $params['organ_id'] = $admin['organ_id'];

        $flag = $this->shopCategorymodel->where('id',$params['category_id'])->where('type',$params['type'])->find();

        if(empty($flag)){
            return error('未知错误');
        }

        if($this->shopCategorymodel->where('parent_id',$flag['id'])->count()){
            return error('不可申请父类目');
        }

        if ($flag['proof_required'] == 1) {
            if (empty($params['industry_qualification'])) {
                return error('需要上传资质证书');
            }
        }else{
            $params['industry_qualification'] = '';
        }

        $this->svalidate($params, ".add");

        $data = Db::transaction(function () use ($params) {
            $this->model->save($params);
        });

        return success('保存成功', $data);

    }


    /**
     * 重新申请
     *
     * @param  $id
     * @return \think\Response
     */
    public function edit(Request $request, $id)
    {

        $admin = $this->auth()->user();

        $params = $this->request->only(['type','category_id', 'industry_qualification']);

        $params['organ_id'] = $admin['organ_id'];

        $params['audit_status'] = 'apply';

        $params['remarks'] = '';

        $flag = $this->shopCategorymodel->where('id',$params['category_id'])->where('type',$params['type'])->find();

        if($this->shopCategorymodel->where('parent_id',$flag['id'])->count()){
            return error('不可申请父类目');
        }

        if(empty($flag)){
            return error('未知错误');
        }

        if ($flag['proof_required'] == 1) {
            if (empty($params['industry_qualification'])) {
                return error('需要上传资质证书');
            }
        }else{
            $params['industry_qualification'] = '';
        }

        $this->svalidate($params,".edit");

        $id = intval($id);

        Db::transaction(function () use ($id, $params,$admin) {

            $data = $this->model->where('id',$id)->where('type',$params['type'])->where('organ_id',$admin->organ_id)->find();
            $data->save($params);

        });

        return success('更新成功');
    }




//    public function audit($id){
//        $id = intval($id);
//        $params = $this->request->only(['audit_status', 'remarks']);
//
//        if(in_array($params['audit_status'],['apply','normal','disabled','reject'])) {
//            Db::transaction(function () use ($id,$params) {
//                $apply = $this->model->where('id',$id)->find();
//                $apply->audit_status = $params['audit_status'] ?? 'apply';
//                $apply->remarks = $params['remarks'] ?? '';
//                $apply->save();
//            });
//            return success('审核成功');
//        }
//        return success('审核成功',$id);
//    }



    /**
     * 获取所有分类，商品选择
     *
     * @return \think\Response
     */
    public function select(Request $request)
    {
        // 获取请求参数中的 'type' 字段
        $params = $this->request->only(['type']);
        $type = isset($params['type']) ? $params['type'] : null;

        // 构建分类查询
        $categories = (new Tree(function () use ($type) {
            // 初始化查询对象
            $query = $this->shopCategorymodel->field("id, name, parent_id, status, weigh")->normal()
                ->order('weigh', 'desc')->order('id', 'asc');

            // 如果 'type' 参数存在，添加到查询条件中
            if (!is_null($type)) {
                $query->where('type', $type);
            }

            return $query;
        }))->getTree(0);

        return success('获取成功', $categories);
    }


}
